package code.Frame.EPFrame;

import code.Frame.FrameManager;
import code.MYSQL;
import code.Main;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.regex.Pattern;

public class DIinput {
    public JPanel panel;
    private JTextField name_txt;
    private JTextField price_txt;
    private JButton confirm;

    private int status;

    private int did;

    private int sid;

    public boolean end = false;

    public DIinput(int s, int id, int sId)
    {
        status = s;
        did = id;
        sid = sId;
        confirm.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                String name = "'" + name_txt.getText() + "'";
                String price = price_txt.getText();
                if (name.length() == 2)
                {
                    JOptionPane.showMessageDialog(panel.getParent(), "菜品名不能为空");
                    return ;
                }
                if (name.length() > 32)
                {
                    JOptionPane.showMessageDialog(panel.getParent(), "菜品名不能超过30位");
                    return ;
                }
                if (price.length() > 6 || !Pattern.compile("[0-9]{1,3}(\\.[0-9]{2})?").matcher(price).matches())
                {
                    JOptionPane.showMessageDialog(panel.getParent(), "价格错误，应为0~999.99之间，小数点后2位");
                    return ;
                }
                if (status == 1) // 修改
                {
                    try
                    {
                        MYSQL.maintain("update dish set " +
                                "name = " + name + ", " +
                                "price = " + price + "\n" +
                                "where DID = " + did
                        );
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
                else // 新增
                {
                    try
                    {
                        MYSQL.maintain("insert into dish(name, price, SID) values( " +
                                name + ", " +
                                price + ", " +
                                sid + ")"
                        );
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
                end = true;
            }
        });
    }
}
